import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus'
// 引入常量路由,异步路由,任意路由
import { staticRoutes,allAsyncRoutes,anyRoutes } from '@/router/routes'
import { reqLogin, reqLogout, reqUserInfo } from '@/api/acl/login';
import router from '@/router';
import _ from 'lodash'
// 定义一个方法,过滤出需要添加的动态路由
const findUersAsnycRoutes = (allAsyncRoutes:any,routes:any)=>{
  // 过滤一级路由
  return allAsyncRoutes.filter((item:any)=>{
    if(routes.indexOf(item.name)!=-1){
      // 过滤二级路由
      if(item.children && item.children.length>0){
        item.children = findUersAsnycRoutes(item.children,routes)
      }
      return true
    }
  })
}

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {

  state: (): UserInfoState => ({
    // 存储token
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: [],
    buttonLists:[]
  }),

  actions: {
    // 登录请求
    async login(username: string, password: string) {
      try {
        // 如果登录成功,则需要持久化存储 token
        // 且仓库中也需要存储 token
        let result = await reqLogin({ username, password })
        // 仓库存储 token
        this.token = result.token
        // 持久化存储 token
        setToken(result.token)
        return 'ok'
      } catch (error) {
        // 如果登录失败,返回promise失败的结果
        return Promise.reject('失败')
      }
    },
    // 获取用户信息
    async getInfo() {
      try {
        let result = await reqUserInfo()
        // 获取用户名和用户头像
        this.name = result.name
        this.avatar = result.avatar
        // 获取按钮,记得在仓库中存储一下,然后记得定义类型
        this.buttonLists = result.buttons
        let userRegisterAsyncRoute = findUersAsnycRoutes(_.cloneDeep(allAsyncRoutes),result.routes)
        this.setRoutes([...userRegisterAsyncRoute,anyRoutes])
        // 菜单展示
        this.menuRoutes = [...staticRoutes,...userRegisterAsyncRoute]
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 定义动态添加路由的方法
    setRoutes(userRoutes:any){
      userRoutes.forEach((item:any)=>{
        router.addRoute(item)
      })
    },

    // 退出登录的请求
    async reset() {
      try {
        await reqLogout()
        // 删除持久化存储的token
        removeToken()
        // 清空用户信息
        this.token = ''
        this.name = ''
        this.avatar = ''
        // 解决bug1
        this.resetRoutes()
        return 'ok'
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 清空路由的方法
    resetRoutes(){
      // 先获取所有路由
      let allRoutes = router.getRoutes()
      // 遍历路由数组,挨个清空
      allRoutes.forEach((item:any)=>{
        router.removeRoute(item.name)
      })
      // 再次获取静态路由
      staticRoutes.forEach((item:any)=>{
        router.addRoute(item)
      })
    }
  },
});
